import { accDiv, accAdd,isArray,isObj,deepClone } from ".";
/**
 * 数组排序
 * @param arr
 * @param type
 * @returns {Array}
 */
export const arraySort = (
  arr: Array<number>,
  type: 1 | 2 = 1
): Array<number> => {
  return arr.sort((a, b) => {
    switch (type) {
      case 1:
        // 正序
        return a - b;
      case 2:
        // 倒序
        return b - a;
      default:
        return 0;
    }
  });
};
/**
 * 数组随机排序
 * @param arr
 * @param type
 * @returns {Array}
 */
export const arrayRandom = <T>(arr: Array<T>): Array<T> => {
  return arr.sort(() => {
    return Math.random() - 0.5;
  });
};
// 数组去重
export const arrayUnique = <T = any>(arr: Array<T>) => {
  return Array.from(new Set(arr));
};
// 两个数组的合集
export const arrayUnion = <T = any>(a: Array<T>, b: Array<T>) => {
  let newArr = a.concat(b);
  return arrayUnique(newArr);
};
// 数组求和
export const sum = (arr: Array<number>) => {
  return arr.reduce((pre, cur) => {
    return accAdd(pre, cur);
  });
};
// 数组平均值
export const average = (arr: Array<number>) => {
  return accDiv(sum(arr), arr.length);
};
/**
 * 指定范围的数组
 * @param start 最小的范围
 * @param end 最大的范围
 * @returns {Array}
 */
export const range = (start: number, end: number): Array<any> => {
  return [...new Array(end + 1).keys()].slice(start);
};
/**
 * 数组转对象
 * @param {Array<[string|number,any]>} arr 需要转换的二维数组
 * @returns {{[string]?:any}} for example : ([['a',1],['b',2]]) => {a:1,b:2}
 */
export const fromPairs = <T = any>(
  arr: Array<[string, T]>
): Record<string, T> => {
  let obj: Record<string, T> = {};
  if (isArray(arr)) {
    arr.forEach((item) => {
      obj[item[0]] = item[1];
    });
  }
  return obj;
};
/**
 * 获取数组的交集
 * @param Array
 * @param Array
 * @returns {Array<T>} for example : ([2,3,4], [2, 3, 4, 7]) => [2, 3]，([3], [2, 3], [1, 3]) => [3]
 */

// [2, 3]
export const intersection = <T>(list: Array<T>, ...arr: Array<Array<T>>): Array<T> =>
  [...new Set(list)].filter((v) => arr.every((b) => b.includes(v)));

type Many<T> = T | ReadonlyArray<T>;
export const castArray = <T>(arr: Many<T>) => {
  if (!arr) {
    return [];
  }
  const value = arr;
  return (Array.isArray(value) ? value : [value]) as T[];
};

/**
 * 数组深度克隆
 */
export const arrayDeepClone = <T extends Array<any>>(arr:T):T|[] => {
	if(isArray(arr)){
		return arr.map(item => {
			if(isObj(item)){
				return deepClone(item,{})
			}else if(isArray(item)){
				return arrayDeepClone(item)
			}
			return item
			
		}) as T
	}
	return [] 
}

